package com.gitee.zjbqdzq;

import com.beust.jcommander.JCommander;
import com.gitee.zjbqdzq.core.Downloader;
import com.gitee.zjbqdzq.core.FfmpegDownloader;
import com.gitee.zjbqdzq.core.NnyyParser;
import com.gitee.zjbqdzq.core.NnyyResource;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class Main {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // https://nnyy.in/_gp/20210647/ep40
    // https://nnyy.in/dianshiju/
    public static void main(String[] args) throws IOException {
        extracted(args);
    }

    private static void extracted(String[] args) throws IOException {
        Commander commander = new Commander();
        JCommander jCommander = JCommander.newBuilder().addObject(commander).build();

        jCommander.parse(args);
        if (commander.isHelp()) {
            jCommander.usage();
            return;
        }
        extracted(commander);
        executorService.execute(() -> System.out.println("开始运行"));
    }

    private static void extracted(Commander commander) throws IOException {
        Downloader downloader = new FfmpegDownloader(commander);
        NnyyParser nnyyParser = new NnyyParser(commander.getId(), commander.getSaveFolder());
        Flux<NnyyResource> parse = nnyyParser.parse();
        parse.subscribe(
                v -> executorService.execute(() -> getDownload(v, downloader)),
                err -> log.error(err.getMessage(), err),
                executorService::shutdown
        );
    }

    private static void getDownload(NnyyResource resource, Downloader downloader) {
        try {
            downloader.download(resource.getUrl(), resource.getFilename());
        } catch (IOException e) {
            log.error("{} 下载失败，原因:", resource.getFilename(), e);
        }
    }
}
